<!-- eslint-disable vue/no-template-shadow -->
<template>
  <div>
    <BasicTable @register="registerTable">
      <template #expandedRowRender="{ record }">
        <BasicTable
          @register="registerChildrenTable"
          :data-source="record.listwff"
          style="max-width: 65%"
        >
          <!-- 图档分类 -->
          <template #isRoot="{ text: isRoot }">
            <Tag :color="isRoot === '0' ? 'success' : 'error'">{{
              isRoot === '0' ? '对象' : '参考文档'
            }}</Tag>
          </template>
          <template #action="{ record }">
            <TableAction
              :actions="[
                {
                  label: t('common.preview'),
                  icon: 'icon-park-outline:preview-open',
                  onClick: handlePreview.bind(null, record),
                  auth: 'processManager:flowToDo:preview',
                },
                {
                  label: t('common.download'),
                  icon: 'material-symbols:download-2-outline',
                  onClick: handleDownload.bind(null, record),
                  auth: 'processManager:flowToDo:download',
                },
                {
                  label: t('routes.demo.workFlow.flowToDoPage.comment'),
                  icon: 'material-symbols:add-comment-outline',
                  onClick: handleComment.bind(null, record),
                  ifShow: false,
                  auth: 'processManager:flowToDo:annotate',
                },
                {
                  label: t('common.edit'),
                  icon: 'ant-design:edit-outlined',
                  onClick: handleEdit.bind(null, record),
                  ifShow: false,
                  auth: 'processManager:flowToDo:edit',
                },
                {
                  label: t('routes.demo.workFlow.flowToDoPage.evaluate'),
                  icon: 'material-symbols:comment-outline',
                  onClick: handleEvaluate.bind(null, record),
                  ifShow: false,
                  auth: 'processManager:flowToDo:evaluate',
                },
              ]"
            />
          </template>
        </BasicTable>
      </template>
      <!-- 建立时间 -->
      <template #createtime="{ text: createtime }">
        <span>
          {{ proxy.$filters.filterTime(createtime) }}
        </span>
      </template>
      <!-- 计划结束时间 -->
      <template #planendtime="{ text: planendtime }">
        <span>
          {{ proxy.$filters.filterTime(planendtime) }}
        </span>
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              label: t('routes.demo.workFlow.flowToDoPage.sign'),
              popConfirm: {
                title: t('routes.demo.workFlow.flowToDoPage.isSign'),
                placement: 'top',
                confirm: handleSign.bind(null, record),
              },
              auth: 'processManager:flowToDo:sign',
            },
            {
              label: t('routes.demo.workFlow.flowToDoPage.return'),
              popConfirm: {
                title: t('routes.demo.workFlow.flowToDoPage.isReturn'),
                placement: 'top',
                confirm: handleReturn.bind(null, record),
              },
              auth: 'processManager:flowToDo:reject',
            },
            {
              label: t('routes.demo.workFlow.flowToDoPage.view'),
              onClick: handleView.bind(null, record),
              auth: 'processManager:flowToDo:detail',
            },
            {
              label: '流程',
              onClick: handleFlow.bind(null, record),
            },
            {
              label: t('routes.demo.workFlow.flowToDoPage.delete'),
              popConfirm: {
                title: t('routes.demo.workFlow.flowToDoPage.isDelete'),
                placement: 'top',
                confirm: handleDelete.bind(null, record),
              },
              auth: 'processManager:flowToDo:delete',
            },
          ]"
        />
      </template>
    </BasicTable>
    <!-- 批注弹窗 -->
    <BasicModal
      :title="t('routes.demo.workFlow.flowToDoPage.commentPicture')"
      :minHeight="200"
      :destroyOnClose="true"
      v-bind="$attrs"
      @register="registerPz"
      @ok="pzOk"
      @cancel="pzCancel"
    >
      <Row style="line-height: 30px">
        <Col span="6">{{ t('routes.demo.workFlow.flowToDoPage.workflowStep') }}</Col>
        <Col span="18">{{ currentPz.id11 }}</Col>
        <Col span="6">{{ t('routes.demo.workFlow.flowToDoPage.commentPerson') }}</Col>
        <Col span="18">{{ currentPz.person }}</Col>
        <Col span="6">{{ t('routes.demo.workFlow.flowToDoPage.commentTime') }}</Col>
        <Col span="18">{{ currentPz.posDate }}</Col>
      </Row>
      <Row style="margin-top: 5px">
        <Col span="24">
          <Textarea
            :placeholder="t('routes.demo.workFlow.flowToDoPage.commentLimit')"
            :rows="5"
            v-model:value="pz"
          />
        </Col>
      </Row>
    </BasicModal>
    <!-- 评分弹窗 -->
    <BasicModal
      :title="t('routes.demo.workFlow.flowToDoPage.score')"
      :minHeight="100"
      :destroyOnClose="true"
      v-bind="$attrs"
      @register="registerScore"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <Form :model="form" :label-col="{ span: 4 }" :wrapper-col="{ span: 14 }">
        <FormItem
          :label="t('routes.demo.workFlow.flowToDoPage.score')"
          :label-col="{ span: 5, offset: 1 }"
          :wrapper-col="{ span: 12, offset: 1 }"
        >
          <InputNumber :min="0" :max="100" v-model:value="form.projScore" />
        </FormItem>
      </Form>
    </BasicModal>
    <!-- 流程选择模态框 -->
    <BasicModal
      :title="t('routes.demo.workFlow.flowToDoPage.workflowDynamicCustomization')"
      :minHeight="100"
      :width="600"
      :destroyOnClose="true"
      v-bind="$attrs"
      @register="registerSelect"
      @ok="handelOk"
      @cancel="handelCancel"
    >
      <BasicTable
        @register="registerFlowSelectTable"
        :data-source="nextStepList"
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: nextStepChange }"
        :rowKey="(item) => item.stepinid"
      />
    </BasicModal>
    <!-- 流程回退模态框 -->
    <BasicModal
      :title="t('routes.demo.workFlow.flowToDoPage.workflowDynamicCustomization')"
      :minHeight="100"
      :width="600"
      :destroyOnClose="true"
      v-bind="$attrs"
      @register="registerBack"
      @ok="backOk"
      @cancel="backCancel"
    >
      <div>{{ backMessage }}</div>
      <BasicTable
        @register="registerFlowBackTable"
        :data-source="backStepList"
        :rowKey="(item) => item.wfStepId"
      />
    </BasicModal>
    <!-- 流程实例弹窗 -->
    <ProcessInstance @register="registerProcessInstance" />
    <!-- 表单预览 -->
    <formPreview @register="registerFormPreview" />
    <!-- 流程属性 -->
    <initiateFlowCopy @register="registerModalCopy" />
    <!-- onlyOffice预览 -->
    <onlyOffice @register="registerOnlyOfficeModal" />
  </div>
</template>

<script lang="ts" setup>
  import { ref, getCurrentInstance } from 'vue';
  import { Row, Col, Input, Form, FormItem, InputNumber, Tag } from 'ant-design-vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { BasicModal, useModal } from '/@/components/Modal';
  import { useUserStore } from '/@/store/modules/user';
  import { useMessage } from '/@/hooks/web/useMessage';
  import throttle from 'lodash/throttle';

  import {
    getFlowDoneColumns,
    getChildFlowDoneColumns,
    getFlowSelectColumns,
    getFlowBackColumns,
  } from './flowData';

  import {
    getFlowToDoListApi,
    signFlowApi,
    continueSignFlowApi,
    backFlowApi,
    selectBackFlowApi,
    backStepFlowApi,
    deleteFlowApi,
    GetBdPreview,
  } from '/@/api/demo/flow';
  import { downloadFile, DownloadWriteBackBdData } from '/@/api/demo/document';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { handleBrowseFile } from '/@/utils/demo/preview';
  import ProcessInstance from '/@/views/components/ProcessInstance.vue';
  import formPreview from './formPreview.vue';
  import initiateFlowCopy from '/@/views/demo/workFlow/initiateFlowCopy.vue';
  // 引入onlyoffice组件
  import onlyOffice from '/@/views/demo/documentManager/components/onlyOffice.vue';

  const { t } = useI18n();

  const Textarea = Input.TextArea;
  // 弹窗
  const [registerPz, { openModal: openPz }] = useModal();
  const [registerScore, { openModal: openScore }] = useModal();
  const [registerSelect, { openModal: openSelect }] = useModal();
  const [registerBack, { openModal: openBack }] = useModal();
  const [registerProcessInstance, { openModal: openPrecessModal }] = useModal();
  const [registerFormPreview, { openModal: openFormPreview }] = useModal();
  const [registerModalCopy, { openModal: openModalCopy }] = useModal();

  interface Pf {
    projScore: number;
  }

  const currentPz = ref<any>({});
  const pz = ref<string>('');
  const form: Pf = {
    projScore: 0,
  };
  const backMessage = ref<string>('');
  const currentSelectStep = ref<any>({});
  const nextStepList = ref<any[]>([]);
  const selectedRowKeys = ref<any[]>([]);
  const selectNextSteps = ref<any[]>([]);
  const currentBackStep = ref<any>({});
  const backStepList = ref<any[]>([]);
  const currentRow = ref<any>({});

  const useCommonStore = useUserStore();
  const { proxy }: any = getCurrentInstance();
  const { createMessage } = useMessage();

  // 父级表格
  const [registerTable, { reload, getDataSource }] = useTable({
    titleHelpMessage: 'flowToDoIndex',
    columns: getFlowDoneColumns(),
    beforeFetch: (params) => {
      params.state = '0';
      params.userId = useCommonStore.userInfo?.userId;
    },
    api: getFlowToDoListApi,
    fetchSetting: {
      // 当前页传递给后台的字段名称
      pageField: 'CurrentPage',
      // 后台每页显示的数量字段名称
      sizeField: 'PageSizes',
      // 接口返回的表单数据字段名称
      listField: 'items',
      // 接口返回的表格总数字段名称
      totalField: 'totalCount',
    },
    showTableSetting: true, // 显示表格设置工具
    showIndexColumn: false,
    tableSetting: { fullScreen: true }, // 表格设置工具配置
    bordered: true,
    actionColumn: {
      width: 300,
      fixed: 'right',
      title: t('common.action'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
  });
  // 子级表格
  const [registerChildrenTable] = useTable({
    // 分页配置
    columns: getChildFlowDoneColumns(),
    showIndexColumn: false,
    showTableSetting: false, // 表格设置工具配置
    bordered: true,
    pagination: false,
    scroll: { x: 0, y: 0 },
    canResize: false,
    actionColumn: {
      width: 400,
      fixed: 'right',
      title: t('common.action'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
  });

  //流程选择表格
  const [registerFlowSelectTable] = useTable({
    columns: getFlowSelectColumns(),
    showIndexColumn: false,
    showTableSetting: false, // 表格设置工具配置
    bordered: true,
    pagination: false,
    canResize: false,
  });

  //流程退回表格
  const setRowClass = (record: any) => {
    return record.wfStepId === currentRow.value.wfStepId ? 'clickRowStyle' : '';
  };
  const [registerFlowBackTable] = useTable({
    columns: getFlowBackColumns(),
    showIndexColumn: false,
    showTableSetting: false, // 表格设置工具配置
    bordered: true,
    pagination: false,
    canResize: false,
    customRow: (record) => {
      return {
        onclick: () => {
          if (currentBackStep.value.backtype == '1') {
            currentRow.value = record;
          }
        },
      };
    },
    rowClassName: setRowClass,
  });
  // 父级操作点击事件
  // 签字
  const handleSign = (record: Recordable) => {
    currentSelectStep.value = record;
    const SignList = {
      userid: useCommonStore.userInfo?.userId,
      step: record.dh,
    };
    signFlowApi(SignList).then((res) => {
      if (res.length > 0) {
        nextStepList.value = res;
        selectedRowKeys.value = res.map((item) => item.stepinid);
        selectNextSteps.value = res;
        openSelect(true);
      } else {
        reload();
        createMessage.success(t('routes.demo.workFlow.flowToDoPage.signSuccess'));
      }
    });
  };

  // 流程选择事件
  const nextStepChange = (keys) => {
    selectedRowKeys.value = keys;
    // 处理选中行数据
    if (keys.length > 0) {
      const list = [];
      keys.forEach((item) => {
        let obj = nextStepList.value.find((o) => o.stepinid == item);
        list.push(obj);
      });
      selectNextSteps.value = list;
    }
  };
  const handelOk = () => {
    if (selectedRowKeys.value.length > 0) {
      const params = {
        userid: useCommonStore.userInfo?.userId,
        step: currentSelectStep.value.dh,
        listst: selectNextSteps.value,
      };
      continueSignFlowApi(params).then(() => {
        reload();
        createMessage.success(t('routes.demo.workFlow.flowToDoPage.signSuccess'));
      });
      handelCancel();
    }
  };
  const handelCancel = () => {
    openSelect(false);
    selectedRowKeys.value = [];
    selectNextSteps.value = [];
    currentSelectStep.value = {};
  };

  // 退回
  const handleReturn = (record: Recordable) => {
    const params = {
      stepid: record.dh,
    };
    backFlowApi(params).then((res) => {
      if (res != null) {
        currentBackStep.value = res;
        backStepList.value = res.listbs;
        if (res.backtype == '0') {
          backMessage.value = '模板中设定回退步骤为：' + res.backStepName;
        } else if (res.backtype == '1') {
          backMessage.value = '模板中设定回退步骤为：';
          currentRow.value = res.listbs[0];
        }
        openBack(true);
      }
    });
  };
  // 流程回退事件
  const backOk = () => {
    if (currentBackStep.value.backtype == '1') {
      //选择步骤回退
      const params = {
        stepId: currentBackStep.value.stepId,
        selectStepId: currentRow.value.wfStepId,
        userName: useCommonStore.userInfo.username,
      };
      selectBackFlowApi(params)
        .then(() => {
          reload();
          createMessage.success(t('routes.demo.workFlow.flowToDoPage.returnSuccess'));
        })
        .catch((error) => {
          createMessage.error(error.message);
        });
    } else {
      const params = {
        backtype: currentBackStep.value.backtype,
        stepId: currentBackStep.value.stepId,
        backwfStepId: currentBackStep.value.backwfStepId,
        backStepName: currentBackStep.value.backStepName,
        username: useCommonStore.userInfo.username,
        listbs: currentBackStep.value.listbs,
      };
      backStepFlowApi(params)
        .then(() => {
          reload();
          createMessage.success(t('routes.demo.workFlow.flowToDoPage.returnSuccess'));
        })
        .catch((error) => {
          createMessage.error(error.message);
        });
    }
    backCancel();
  };
  const backCancel = () => {
    openBack(false);
    backStepList.value = [];
    backMessage.value = '';
    currentBackStep.value = {};
    currentRow.value = {};
  };

  const handleView = (record: Recordable) => {
    openPrecessModal(true, { wfInsId: record.workflowid });
  };
  const handleDelete = (record: Recordable) => {
    const params = {
      stepInsId: record.dh,
      wfInsId: record.workflowid,
      oId: '',
    };
    deleteFlowApi(params).then(() => {
      reload();
      createMessage.success(t('common.delSuccessText'));
    });
  };

  // 流程属性
  const handleFlow = (record: Recordable) => {
    openModalCopy(true, { record: record, isUpdate: true });
  };

  // 子级操作点击事件
  const handlePreview = async (record: Recordable) => {
    // isfile 0为流程，1为下挂文件,2为表单
    if (record.isfile == '1') {
      // 文件
      await handleBrowseFile(record, '待办流程');
    } else if (record.isfile == '2') {
      // 表单
      GetBdPreview(record.oid).then((res) => {
        openFormPreview(true, { dataList: res });
      });
    }
  };
  const checkBit = (str, index) => {
    if (index < 1 || index > str.length) {
      throw new Error('索引超出范围');
    }
    return str.charAt(index - 1) === '0';
  };
  const handleDownload = throttle((record: Recordable) => {
    // isfile 0为流程，1为下挂文件,2为表单
    if (record.isfile == '1') {
      // 文件
      // 查找当前步骤
      const currentRecord = getDataSource().find((item) => item.dh == record.wfstinid);
      const isPermission =
        record.isRoot === '1' ? checkBit(currentRecord.wfModelData.attrstr, 4) : false;
      if (isPermission) {
        createMessage.error('没有下载权限');
      } else {
        downloadFile(record.oid, record.version, record.filename).then(() => {
          createMessage.success(t('common.downLoadSuccess'));
        });
      }
    } else if (record.isfile == '2') {
      // 表单
      DownloadWriteBackBdData(record.oid, record.step + record.bdExtension).then(() => {
        createMessage.success(t('common.downLoadSuccess'));
      });
    }
  }, 3000);
  const handleComment = (record: Recordable) => {
    openPz(true);
    console.log('点击了批注', record);
  };
  const handleEvaluate = (record: Recordable) => {
    openScore(true);
    console.log('点击了评估', record);
  };

  const [registerOnlyOfficeModal, { openModal: openPreviewModal }] = useModal();
  // 编辑
  const handleEdit = (record: Recordable) => {
    // isfile 0为流程，1为下挂文件,2为表单
    if (record.isfile == '1') {
      // 文件 isRoot 0为对象 1 为参考文档
      if (record.isRoot == '0') {
        // 查找当前步骤
        const currentRecord = getDataSource().find((item) => item.dh == record.wfstinid);
        const isPermission =
          record.isRoot === '1' ? checkBit(currentRecord.wfModelData.attrstr, 2) : false;
        if (isPermission) {
          createMessage.error('没有编辑权限');
        } else {
          const configList = {
            oId: record.oid,
            version: record.version,
            userId: useCommonStore.userInfo.userId,
            mode: 'edit',
          };
          openPreviewModal(true, { configList });
        }
      } else if (record.isRoot == '1') {
        createMessage.error('参考文档无法编辑');
      }
    } else if (record.isfile == '2') {
      // 表单
      createMessage.error('暂无表单编辑接口');
    }
  };

  // 批注事件
  const pzOk = () => {
    console.log('批注成功');
  };
  const pzCancel = () => {
    console.log('批注取消');
  };

  // 评分事件
  const handleOk = () => {
    console.log('评分成功');
  };
  const handleCancel = () => {
    console.log('评分取消');
  };
</script>
<style lang="less" scoped>
  ::v-deep(.ant-table-scroll) {
    overflow: auto !important;
  }

  ::v-deep(.clickRowStyle) {
    cursor: pointer !important;
    background-color: #32b4f0 !important;
  }
</style>
